import 'package:flutter/material.dart';
import 'package:schoollifedemo/base/url_contract.dart';
import 'package:schoollifedemo/business/home/viewmodel/home_page_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/button_widget.dart';
import 'package:schoollifedemo/commonwidget/circle_empty_widget.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/commonwidget/common_friend_circle_message_widget.dart';
import 'package:schoollifedemo/commonwidget/error_widget.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/entity/Entity.dart';
import 'package:schoollifedemo/localization/local_text.dart';

class HomePage extends BaseStatefulPage {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends BasePageState<HomePage> {
  final HomePageViewModel _viewModel = HomePageViewModel();
  ScrollController? _scrollController;

  String commitText = '';
  int currentIndex = 0;

  @override
  void initState() {
    _viewModel.init();
    _viewModel.pullFriendCircleMessageList(onFailure: (msg) {
      DialogUtils.showTitleAndMessageDialog(
        context,
        clickOutSideDismiss: true,
        title: "错误",
        msg: "result error pull FriendCircleMessageList: $msg",
      );
    });
    _viewModel.pullLatestWeather(onFailure: (msg) {
      DialogUtils.showTitleAndMessageDialog(
        context,
        clickOutSideDismiss: true,
        title: "错误",
        msg: "result error weather resp: $msg",
      );
    });
    _scrollController = ScrollController();
    _scrollController?.addListener(() {
      if (_scrollController?.position.pixels ==
          _scrollController?.position.maxScrollExtent) {
        // 是否到了底部，到了底部进行刷新
        _viewModel.pullFriendCircleMessageList(
            currentPage: (_viewModel.messageResp?.currentPage ?? 0) + 1,
            onFailure: (msg) {
              DialogUtils.showTitleAndMessageDialog(
                context,
                clickOutSideDismiss: true,
                title: "错误",
                msg: "result error pull FriendCircleMessageList: $msg",
              );
            });
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      initialData: CommonLoadingState.loading,
      stream: _viewModel.loadingState,
      builder: (buildContext, snapshot) {
        CommonLoadingState? loadingState = snapshot.data as CommonLoadingState?;
        switch (loadingState) {
          case CommonLoadingState.loading: // 加载状态，进入时加载
            return const Scaffold(
              body: LoadingWidget(),
            );
          case CommonLoadingState.successTypeOne:
          case CommonLoadingState.successTypeTwo:
            return Scaffold(
              body: _commonBody(),
              floatingActionButton: GestureDetector(
                onTap: () async {
                  await _viewModel.turnToEditFriendCirclePage(context);
                  _viewModel.pullFriendCircleMessageList();
                },
                child: ClipOval(
                  child: Container(
                    width: 38,
                    height: 38,
                    color: const Color(0xFFD0E7FF),
                    child: Center(
                      child: SizedBox(
                        width: 28,
                        height: 28,
                        child: Image.asset(
                          'assets/images/common/icon_add.png',
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            );
          case CommonLoadingState.failure:
            return Scaffold(
              body: CommonErrorWidget(
                '网络错误',
                onButtonClick: () {
                  _viewModel.pullLatestWeather(onFailure: (msg) {
                    DialogUtils.showTitleAndMessageDialog(
                      context,
                      clickOutSideDismiss: true,
                      title: "错误",
                      msg: "result error weather resp: $msg",
                    );
                  });
                  _viewModel.pullFriendCircleMessageList(onFailure: (msg) {
                    DialogUtils.showTitleAndMessageDialog(
                      context,
                      clickOutSideDismiss: true,
                      title: "错误",
                      msg: "result error pull FriendCircleMessageList: $msg",
                    );
                  });
                },
              ),
            );
          default:
            return Scaffold(
              body: Container(),
            );
        }
      },
    );
  }

  Widget _commonBody() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(bottom: 20),
      child: MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: RefreshIndicator(
          onRefresh: () async {
            _viewModel.pullLatestWeather(onFailure: (msg) {
              DialogUtils.showTitleAndMessageDialog(
                context,
                clickOutSideDismiss: true,
                title: "错误",
                msg: "result error weather resp: $msg",
              );
            });
            _viewModel.pullFriendCircleMessageList(
                refreshQuickly: true,
                onFailure: (msg) {
                  DialogUtils.showTitleAndMessageDialog(
                    context,
                    clickOutSideDismiss: true,
                    title: "错误",
                    msg: "result error pull FriendCircleMessageList: $msg",
                  );
                });
          },
          child: ListView(
            controller: _scrollController,
            physics: const BouncingScrollPhysics(),
            children: [
              const TextWidgetWithOverflow(
                HomeLocalText.todayWeather,
                textAlign: TextAlign.left,
                insideColor: Colors.white,
                paddingLeft: 20,
                fontSize: 28,
                fontWeight: FontWeight.w400,
                paddingTop: 20,
              ),
              Padding(
                padding: const EdgeInsets.only(left: 15, right: 15, top: 5),
                child: CircleEmptyWidget(
                  _weatherWidget(
                    weatherType:
                        _viewModel.weatherResp?.weatherMessage?.weatherType ??
                            '',
                    date: _viewModel.weatherResp?.weatherMessage?.date ?? '',
                    location:
                        _viewModel.weatherResp?.weatherMessage?.location ?? '',
                    temperature:
                        '${_viewModel.weatherResp?.weatherMessage?.temperature} ℃',
                  ),
                  height: 60,
                  insideColor: const Color(0xFF529FE8),
                ),
              ),
              const TextWidgetWithOverflow(
                HomeLocalText.yourFriendCircle,
                textAlign: TextAlign.left,
                insideColor: Colors.white,
                paddingLeft: 20,
                fontSize: 28,
                fontWeight: FontWeight.w400,
                paddingTop: 20,
              ),
              Offstage(
                offstage:
                    (_viewModel.messageResp?.messageList?.length ?? 0) > 0,
                child: Column(
                  children: [
                    Container(
                      margin: EdgeInsets.only(top: 10),
                      child: Center(
                        child: Image.asset(
                          'assets/images/home/img_friend_circle_empty.png',
                          width: 200,
                          height: 200,
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () async {
                        await _viewModel.turnToEditFriendCirclePage(context);
                        _viewModel.pullFriendCircleMessageList();
                      },
                      child: Container(
                        margin: const EdgeInsets.only(top: 20),
                        child: const TextWidgetWithOverflow(
                          '目前没有朋友圈~\n编辑一条朋友圈?',
                          fontSize: 18,
                          paddingLeft: 20,
                          paddingRight: 20,
                          height: 66,
                          maxLine: 2,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (buildContext, index) {
                  FriendCircleMessage? friendCircleMessage =
                      _viewModel.messageResp?.messageList?[index];
                  return CommonFriendCircleMessageWidget(
                    friendCircleMessage,
                    onCommitClick: () {
                      _viewModel.onCommit(context, index);
                    },
                    onLoveClick: () {
                      _viewModel.onLove(context, index);
                    },
                    onUnLoveClick: () {
                      _viewModel.onUnLove(context, index);
                    },
                    onIconClick: () async {
                      _viewModel.pullPersonalInfo(
                        friendCircleMessage?.account,
                        onSuccess: (value) {
                          final personInfo = value as PersonalInfoResponse?;

                          DialogUtils.showPersonalInfoCupertinoDialog(
                            context,
                            clickOutSideDismiss: true,
                            title: '个人信息',
                            iconSrc: personInfo?.icon?.iconSrc,
                            nickname: personInfo?.nickname,
                            personalProfile: personInfo?.personalProfile,
                          );
                        },
                        onFailure: (msg) {
                          DialogUtils.showTitleAndMessageDialog(
                            context,
                            clickOutSideDismiss: true,
                            title: '错误',
                            msg: msg,
                          );
                        },
                      );
                    },
                    onCommitItemClick: (context, commitIndex) {
                      DialogUtils.showSimpleCupertinoDialog(
                        context,
                        clickOutSideDismiss: true,
                        widgets: Column(
                          children: [
                            Offstage(
                              offstage: _viewModel
                                      .messageResp
                                      ?.messageList?[index]
                                      .commitList?[commitIndex]
                                      ?.commitUser
                                      ?.account !=
                                  _viewModel.getApplication().getLoginAccount(),
                              child: ButtonWidget(
                                insideWidget: const TextWidgetWithOverflow(
                                  '删除评论',
                                  fontSize: 14,
                                  insideColor: Colors.transparent,
                                  textColor: Colors.white,
                                ),
                                width: double.infinity,
                                onButtonClick: () async {
                                  // 删除评论
                                  Navigator.pop(context);
                                  String? conversationId =
                                      friendCircleMessage?.conversationId;
                                  String? commitId = friendCircleMessage
                                      ?.commitList?[commitIndex]?.commitId;
                                  bool? deleteResult =
                                      await _viewModel.deleteCommit(
                                    conversationId: conversationId ?? '',
                                    commitId: commitId ?? '',
                                  );
                                },
                              ),
                            ),
                            ButtonWidget(
                              insideWidget: const TextWidgetWithOverflow(
                                '评论该评论',
                                fontSize: 14,
                                textColor: Colors.white,
                                insideColor: Colors.transparent,
                              ),
                              width: double.infinity,
                              onButtonClick: () async {
                                // 对评论进行评论
                                Navigator.pop(context);
                                Future.delayed(
                                  const Duration(microseconds: 500),
                                  () {
                                    DialogUtils.showEditCommitDialog(
                                      context,
                                      onBackClick: () {
                                        Navigator.pop(context);
                                      },
                                      onCancelClick: () {
                                        Navigator.pop(context);
                                      },
                                      onConfirmClick: () {
                                        String? conversationId =
                                            friendCircleMessage?.conversationId;
                                        String? toWho =
                                            friendCircleMessage?.account;
                                        _viewModel.commitToWhoCommit(
                                          conversationId: conversationId ?? '',
                                          toWho: toWho ?? '',
                                          msg: commitText,
                                        );
                                      },
                                      onTextChange: (text) {
                                        commitText = text;
                                      },
                                    );
                                  },
                                );
                              },
                            ),
                          ],
                        ),
                      );
                    },
                  );
                  // return Container();
                },
                separatorBuilder: (buildContext, index) {
                  return const SizedBox(
                    height: 10,
                  );
                },
                itemCount: _viewModel.messageResp?.messageList?.length ?? 0,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _insideDialogWidget({
    String? iconSrc,
    String? nickname,
    String? personalProfile,
  }) {
    return Container(
      height: 280,
      margin: const EdgeInsets.only(left: 10, right: 10),
      child: CircleEmptyWidget(
        IntrinsicHeight(
          child: ListView(
            physics: const BouncingScrollPhysics(),
            children: [
              Center(
                child: ClipOval(
                  child: Container(
                    width: 60,
                    height: 60,
                    child: Image.network(_getIconAddress(iconSrc ?? '')),
                  ),
                ),
              ),
              TextWidgetWithOverflow(
                nickname ?? '',
                fontSize: 16,
                insideColor: Colors.transparent,
              ),
              Expanded(
                child: Container(
                  margin:
                      const EdgeInsets.only(left: 10, right: 10, bottom: 10),
                  child: TextWidgetWithOverflow(
                    personalProfile ?? '',
                    fontSize: 15,
                    insideColor: Colors.white,
                    maxLine: 10,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _weatherWidget({
    required String weatherType, // 天气状态
    required String temperature, // 温度
    required String location, // 位置
    required String date, // 当前日期
  }) {
    return Row(
      children: [
        Expanded(
          child: CircleEmptyWidget(
            Row(
              children: [
                const Padding(
                  padding: EdgeInsets.only(left: 5),
                  child: TextWidgetWithOverflow(
                    HomeLocalText.todayWeather,
                    maxLine: 2,
                    width: 100,
                    height: 50,
                    fontSize: 16,
                    fontWeight: FontWeight.w400,
                    insideColor: Colors.transparent,
                  ),
                ),
                Expanded(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(right: 10),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text('$weatherType $temperature'),
                            Text(location),
                          ],
                        ),
                      ),
                      const Padding(
                        padding: EdgeInsets.only(right: 20),
                        child: Icon(Icons.wb_sunny),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            insideColor: const Color(0xFFD0E7FF),
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(right: 10),
          child: TextWidgetWithOverflow(
            _convertToDate(date),
            textAlign: TextAlign.center,
            fontSize: 16,
            width: 80,
            textColor: Colors.white,
            maxLine: 2,
          ),
        ),
      ],
    );
  }

  String _getIconAddress(String iconSrc) {
    return UrlContract.baseAddress + '/' + iconSrc;
  }

  String _convertToDate(String timeStamps) {
    final time = int.tryParse(timeStamps);
    if (time == null) {
      return '';
    }
    final dateTime = DateTime.fromMillisecondsSinceEpoch(time);
    return '${dateTime.year}年${dateTime.month}月${dateTime.day}日';
  }
}
